package demo;

class MyBlockingQueues{
    private static int[] arr=new int[1000];
    private static int size=0;
    private static int start=0;
    private static int end=0;
    private static Object object=new Object();
    public static void put(int value) throws InterruptedException {
        synchronized(object){
            if(size==arr.length){
                object.wait();
            }
            arr[end]=value;
            end++;
            if(end==arr.length){
                end=0;
            }
            size++;
            object.notify();
        }
    }
    public static int take() throws InterruptedException {
        synchronized(object){
            if(size==0){
                object.wait();
            }
            int tmp=arr[start];
            start++;
            if(start==arr.length){
                start=0;
            }
            size--;
            object.notify();
            return tmp;
        }
    }
}
public class blocking {
    public static MyBlockingQueues myBlockingQueues=new MyBlockingQueues();
    public static void main(String[] args) {
        Thread t1=new Thread(()->{
            int n=0;
            while (true){
                try {
                    System.out.println("生产："+n);
                    myBlockingQueues.put(n);
                    n++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();

        Thread t2=new Thread(()->{
            while (true){
                try {
                    Thread.sleep(3000);
                    System.out.print("消费：");
                    int tmp=myBlockingQueues.take();
                    System.out.println(tmp);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
}
